package com.joysuch.wwyt.dynamicdata.processor;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import com.joysuch.wwyt.common.constant.Constant;
import com.joysuch.wwyt.core.common.util.SpringContextUtils;
import com.joysuch.wwyt.dynamicdata.DynamicDataConstants;
import com.joysuch.wwyt.dynamicdata.DynamicParam;
import com.joysuch.wwyt.dynamicdata.entity.BaseDynamicData;
import com.joysuch.wwyt.dynamicdata.service.BaseDynamicDataService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DynamicDataSelectProcessor extends AbstractDynamicDataProcessor implements IDynamicDataProcessor {

    private final BaseDynamicDataService dynamicDataService;

    public DynamicDataSelectProcessor() {
        this.dynamicDataService = SpringContextUtils.getBean(BaseDynamicDataService.class);
    }

    @Override
    public Object doProcess(DynamicParam param) {
        Object object = param.getTargetData();
        Object result;
        if (object instanceof List<?>) {
            List<Object> objectList = new ArrayList<>();
            for (Object data : (List<?>) object) {
                Object newObj = buildNewObject(data);
                objectList.add(newObj);
            }
            result = objectList;
        } else {
            result = buildNewObject(object);
        }
        return result;
    }

    private Object buildNewObject(Object object) {
        Map<String, Object> properties = Maps.newHashMap();
        JSONObject jsonObject = JSONUtil.parseObj(object);
        List<BaseDynamicData> dataList = dynamicDataService.findDataByBizId(Long.valueOf(jsonObject.get(DynamicDataConstants.ID).toString()));
        dataList.forEach(each -> properties.put(each.getFieldName(), each.getFieldValue() != null ? each.getFieldValue() : Constant.EMPTY_STR));
        return addTargetField(object, properties);
    }
}
